#pragma once

#include <iostream>
#include "Tcpsocket.hpp"
#include "log.hpp"
#include <signal.h>
#include <functional>
#include <string>


using func_t = std::function<std::string(std::string &package)>;

class TcpServer
{
public:
    TcpServer(uint16_t port,func_t callback)
        : _port(port),_callback(callback)
    {
    }

    bool Initserver()
    {
        _sock.Socket();
        _sock.Bind(_port);
        _sock.Listen();
        lg(Info, "init server .... done");
        return true;
    }

    void Start()
    {
        signal(SIGCHLD, SIG_IGN);
        signal(SIGPIPE, SIG_IGN);
        while (1)
        {
            std::string clientip;
            uint16_t clientport;
            int sockfd = _sock.Accept(&clientip, &clientport);
            if (sockfd < 0)
                continue;
            lg(Info, "accept a new link, sockfd: %d, clientip: %s, clientport: %d", sockfd, clientip.c_str(), clientport);
            if (fork() == 0)
            {
                _sock.Close();
                std::string inbuffer_stream;
                while (1)
                {
                    char buffer[1280];
                    int n = read(sockfd, buffer, sizeof(buffer));
                    if (n > 0)
                    {
                        buffer[n] = 0;
                        inbuffer_stream += buffer;
                        // lg(Debug, "debug:\n%s", inbuffer_stream.c_str());
                        // int cut=1;
                        while (1)
                        {
                            std::string tmp = _callback(inbuffer_stream);
                            if (tmp.size() == 0)
                                break;
                            lg(Debug, "debug, response:\n%s", tmp.c_str());
                            //lg(Debug, "debug:\n%s", inbuffer_stream.c_str());
                            write(sockfd, tmp.c_str(), tmp.size());
                        }
                    }
                    else if(n==0)
                        break;
                    else 
                        break;
                }
                exit(0);
            }
            close(sockfd);
        }
    }

private:
    sock _sock;
    // int _listensock;
    func_t _callback;
    uint16_t _port;
    // std::string _ip;
};